package com.itheima.web.controller.front;

import com.itheima.core.BaseServlet;
import com.itheima.core.ResponseBody;
import com.itheima.domain.front.ExamPaper;
import com.itheima.domain.front.Member;
import com.itheima.service.front.MemberService;
import com.itheima.service.front.impl.MemberServiceImpl;
import com.itheima.web.controller.Code;
import com.itheima.web.controller.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/member/*")
public class MemberServlet extends BaseServlet {

    private MemberService memberService = new MemberServiceImpl();

    /*注册*/
    @ResponseBody
    public Result register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Member member = getData(request, Member.class);
        System.out.println(member);
        boolean register = memberService.register(member);
        if (register) {
            return new Result("注册成功！", true,null,Code.SUCCESS);
        } else {
            return new Result("邮箱已被注册", false, null, Code.FAIL);
        }
    }
    @ResponseBody
    public Result login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Member member = getData(request,Member.class);
        member = memberService.login(member.getEmail(),member.getPassword());
        if(member != null){
            // request.setAttribute("localStorage",member);
            return new Result("登录成功！", member);
        }else{
            return new Result("用户名密码错误，请重试！", false, null, Code.LOGIN_FAIL);
        }
    }

    @ResponseBody
    public Result checkLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Member member = getData(request,Member.class);
        //根据获取到的id去redis中查找，是否存在
        String nickName = memberService.getLoginInfo(member.getId());
        return new Result("", nickName);
    }

    @ResponseBody
    public Result logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Member member = getData(request,Member.class);
        boolean flag = memberService.logout(member.getId());
        if(flag){
            return new Result("退出成功!", flag);
        }else{
            return new Result("", false, flag, Code.LOGOUT_FAIL);
        }
    }


    @ResponseBody
    public Result myExaminationPaper(HttpServletRequest request, HttpServletResponse response){
        String memberId = request.getParameter("id");

        List<ExamPaper> papers = memberService.findByMemberId(memberId);


        return new Result("查询历史测试成功",true,papers,Code.SUCCESS);
    }

}

